// 作品历史页面：展示当前用户生成图片的历史记录，并提供删除、公开设置、点赞功能
// - 进入页面后：POST /api/work/listMyWorksRoute，携带 page、page_size，且请求头需带 token（已在拦截器处理）
// - 弹窗展示详情（封装为子组件）
// - UI：Tailwind；支持 PC/移动端、暗黑模式

import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { request } from "@/utils/request";
import { getStoredBearerToken, hasStoredToken } from "@/utils/auth";
import { useI18n } from '@/utils/in18';
import WorkDetailModal, { WorkItem } from "./components/WorkDetailModal";

type ListResponse = {
  success: boolean;
  data: WorkItem[];
  total: number;
  page: number;
  page_size: number;
};

// 分页页大小常量
const DEFAULT_PAGE_SIZE = 2;

const MyWorkPage: React.FC = () => {
  // 列表与分页状态
  const [items, setItems] = useState<WorkItem[]>([]);
  const [page, setPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(DEFAULT_PAGE_SIZE);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);

  // 详情弹窗状态
  const [detailOpen, setDetailOpen] = useState<boolean>(false);
  const [current, setCurrent] = useState<WorkItem | null>(null);
  // 管理/编辑模式用于多选删除
  const [editMode, setEditMode] = useState<boolean>(false);
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [confirmOpen, setConfirmOpen] = useState<boolean>(false);
  const [confirmLanguage, setConfirmLanguage] = useState<string>('');

  const navigate = useNavigate();
  const { t } = useI18n();
  const goBack = useCallback(() => {
    try {
      if (window.history.length > 1) {
        navigate(-1);
      } else {
        navigate("/");
      }
    } catch {
      navigate("/");
    }
  }, [navigate]);

  // 加载我的作品列表（初始加载或刷新 - 替换数据）
  const fetchList = useCallback(async (p = page, ps = pageSize) => {
    if (!hasStoredToken()) return;
    setLoading(true);
    try {
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;
      const resp = await request.post<ListResponse>("/api/work/listMyWorksRoute", { page: p, page_size: ps }, { headers: { Authorization: authHeader } });
      const list = resp?.data?.data || [];
      setItems(list);
      setTotal(resp?.data?.total || 0);
      setPage(resp?.data?.page || p);
      setPageSize(resp?.data?.page_size || ps);
    } catch (e) {
      // 错误提示已在拦截器处理
    } finally {
      setLoading(false);
    }
  }, [page, pageSize]);

  // 滚动懒加载：加载下一页并追加（避免重复）
  const loadingMoreRef = useRef(false);
  const observerRef = useRef<IntersectionObserver | null>(null);
  const sentinelRef = useRef<HTMLDivElement | null>(null);

  const fetchMore = useCallback(async () => {
    if (loading || loadingMoreRef.current) return;
    if (!hasStoredToken()) return;
    const nextPage = Math.min(Math.max(1, page + 1), Math.max(1, Math.ceil(total / pageSize)));
    // 如果没有更多页直接返回
    if (page >= Math.ceil(total / pageSize)) return;

    loadingMoreRef.current = true;
    try {
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;
      const resp = await request.post<ListResponse>("/api/work/listMyWorksRoute", { page: nextPage, page_size: pageSize }, { headers: { Authorization: authHeader } });
      const list = resp?.data?.data || [];
      // 通过 id 去重，避免重复追加
      setItems((prev) => {
        const existingIds = new Set(prev.map((it) => it.id));
        const filtered = list.filter((it) => !existingIds.has(it.id));
        if (filtered.length === 0) return prev; // 防止闪烁或重复替换
        return [...prev, ...filtered];
      });
      setTotal(resp?.data?.total ?? total);
      setPage(nextPage);
    } catch (e) {
      // ignore
    } finally {
      loadingMoreRef.current = false;
    }
  }, [loading, page, pageSize, total]);

  useEffect(() => {
    fetchList(1, pageSize);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 绑定 IntersectionObserver 到 sentinel，用于触发加载更多
  useEffect(() => {
    if (!sentinelRef.current) return;
    if (observerRef.current) observerRef.current.disconnect();
    observerRef.current = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          fetchMore();
        }
      });
    }, { root: null, rootMargin: '200px', threshold: 0.01 });
    observerRef.current.observe(sentinelRef.current);
    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
        observerRef.current = null;
      }
    };
  }, [fetchMore]);

  // 打开详情弹窗
  const openDetail = (work: WorkItem) => {
    setCurrent(work);
    setDetailOpen(true);
  };

  const toggleSelect = (id: number) => {
    setSelectedIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
  };

  const handleConfirmBulkDelete = useCallback(async () => {
    if (selectedIds.length === 0) return;
    try {
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;
      const payload: any = { work_id: selectedIds };
      if (confirmLanguage) payload.language = confirmLanguage;
      const resp = await request.post<{ success: boolean }>("/api/work/deleteWorkRoute", payload, { headers: { Authorization: authHeader } });
      if (resp?.data?.success) {
        setItems((prev) => prev.filter((it) => !selectedIds.includes(it.id)));
        setTotal((t) => Math.max(0, t - selectedIds.length));
        setSelectedIds([]);
        setConfirmOpen(false);
        setEditMode(false);
        if (current && selectedIds.includes(current.id)) {
          setDetailOpen(false);
          setCurrent(null);
        }
      }
    } catch (e) {
      // ignore
    }
  }, [selectedIds, confirmLanguage, current]);

  // 点赞/取消点赞
  const handleToggleLike = useCallback(async (workId: number) => {
    try {
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;
      // 后端返回示例：{ success: true, is_liked: true, likes_count: 1 }
      const resp = await request.post<{ success: boolean; is_liked: boolean; likes_count?: number }>("/api/work/toggleWorkLikeRoute", { work_id: workId }, { headers: { Authorization: authHeader } });
      if (resp?.data?.success) {
        const isLiked = resp?.data?.is_liked;
        const returnedLikes = typeof resp?.data?.likes_count === 'number' ? resp.data.likes_count : undefined;

        setItems((prev) => prev.map((it) =>
          it.id === workId
            ? { ...it, is_liked: isLiked, likes_count: returnedLikes ?? Math.max(0, (it.likes_count || 0) + (isLiked ? 1 : -1)) }
            : it
        ));

        setCurrent((cur) =>
          cur && cur.id === workId
            ? { ...cur, is_liked: isLiked, likes_count: returnedLikes ?? Math.max(0, (cur.likes_count || 0) + (isLiked ? 1 : -1)) }
            : cur
        );
      }
    } catch { }
  }, []);

  // 删除作品
  const handleDelete = useCallback(async (workId: number) => {
    try {
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;
      const resp = await request.post<{ success: boolean }>("/api/work/deleteWorkRoute", { work_id: workId }, { headers: { Authorization: authHeader } });
      if (resp?.data?.success) {
        setItems((prev) => prev.filter((it) => it.id !== workId));
        setTotal((t) => Math.max(0, t - 1));
        if (current?.id === workId) {
          setDetailOpen(false);
          setCurrent(null);
        }
      }
    } catch { }
  }, [current]);

  // 切换公开/私密
  const handleTogglePublic = useCallback(async (workId: number, nextPublic: boolean) => {
    try {
      const authHeader = getStoredBearerToken();
      if (!authHeader) return;
      const resp = await request.post<{ success: boolean }>("/api/work/updateWorkVisibilityRoute", { work_id: workId, is_public: nextPublic }, { headers: { Authorization: authHeader } });
      if (resp?.data?.success) {
        setItems((prev) => prev.map((it) => it.id === workId ? { ...it, is_public: nextPublic } : it));
        setCurrent((cur) => cur && cur.id === workId ? { ...cur, is_public: nextPublic } : cur);
      }
    } catch { }
  }, []);

  const totalPages = useMemo(() => Math.max(1, Math.ceil(total / pageSize)), [total, pageSize]);

  // 翻页
  const goPage = (p: number) => {
    const np = Math.min(Math.max(1, p), totalPages);
    setPage(np);
    fetchList(np, pageSize);
  };

  return (
    <div className="w-full md:w-[70%] mx-auto px-4 md:px-6 md:py-6 min-h-[var(--content-h)] sm:min-h-full">
      {/* 自定义返回标题栏 */}
      <div className="sticky justify-between top-0 z-20 bg-white/80 dark:bg-[#111111]/80 backdrop-blur border-b border-gray-200 dark:border-gray-800 h-14 flex items-center ">
        {/* 返回按钮  */}
          <button
          className="rounded flex items-center text-black dark:text-white hover:bg-gray-100 dark:hover:bg-[#1a1a1a]"
          aria-label={t('my_work.back')}
        >
          <svg onClick={goBack} viewBox="0 0 24 24" width="22" height="22" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M15 18l-6-6 6-6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
          {/* 标题  */}
          <div>
            <h2 className="text-base md:text-lg font-semibold text-gray-900 dark:text-gray-100">{t('my_work.title')}</h2>
          </div>
        </button>

        {/* 管理按钮（右侧） */}
        <div className=" flex items-center gap-2">
          {editMode && (
            <span
              onClick={() => setConfirmOpen(true)}
              className="px-3 py-1 rounded bg-red-500 text-white text-sm"
            >
              {t('my_work.delete_selected')}
            </span>
          )}
          <span
            onClick={() => {
              setEditMode((v) => !v);
              if (editMode) setSelectedIds([]);
            }}
            className="px-3 py-1  dark:bg-gray-100 bg-[#111] dark:text-black text-sm rounded"
          >
            {editMode ? t('my_work.cancel') : t('my_work.management')}
          </span>
        </div>
      </div>

      {/* 列表区域 */}
      <div className="mt-4 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-4">
        {loading && (
          <div className="col-span-full text-center text-sm text-gray-500 dark:text-gray-400">{t('my_work.loading')}</div>
        )}

        {!loading && items.length === 0 && (
          <div className="col-span-full text-center text-sm text-gray-500 dark:text-gray-400">{t('my_work.no_works')}</div>
        )}

        {!loading && items.map((it) => {
          const created = it.createdAt ? new Date(it.createdAt).toLocaleDateString() : "";
          return (
            <div key={it.id} className="group relative rounded-xl overflow-hidden border border-gray-200 dark:border-gray-700 bg-white dark:bg-[#0b0b0b] shadow-sm">
              {/* 勾选框  */}
              {editMode && (
                <input
                  type="checkbox"
                  checked={selectedIds.includes(it.id)}
                  onChange={() => toggleSelect(it.id)}
                  className="absolute top-2 left-2 z-30 w-5 h-5"
                />
              )}
              <button className="block w-full" onClick={() => openDetail(it)}>
                <div className="relative w-full" style={{ paddingTop: '167.1875%' }}>
                  <img src={it.image_url} alt={t('my_work.image_alt')} className="absolute inset-0 w-full h-full object-cover" />
                </div>
              </button>
              <div className="p-2 sm:p-3 text-xs sm:text-sm flex items-center justify-between">
                <div className="text-gray-700 dark:text-gray-200">{created}</div>
                <div className="flex items-center gap-2">
                  <button onClick={() => handleToggleLike(it.id)} className="inline-flex items-center gap-1 px-2 py-1 rounded hover:bg-gray-100 dark:hover:bg-[#111]">
                    <span className={it.is_liked ? "text-red-500" : "text-gray-500"}>
                      <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2507" width="18" height="18" className="text-inherit"><path d="M512 998.4c-19.2 0-38.4-12.8-38.4-19.2C454.4 966.4 128 640 83.2 595.2 32 537.6 0 467.2 0 396.8s32-147.2 83.2-198.4c51.2-51.2 121.6-83.2 198.4-83.2 76.8 0 147.2 32 198.4 83.2C492.8 211.2 505.6 224 512 236.8c6.4-12.8 19.2-25.6 32-38.4 51.2-51.2 121.6-83.2 198.4-83.2 76.8 0 147.2 32 198.4 83.2C992 249.6 1024 320 1024 396.8c0 76.8-32 147.2-83.2 198.4C896 640 569.6 966.4 550.4 979.2 550.4 985.6 531.2 998.4 512 998.4z" fill="currentColor" p-id="2346"></path></svg>
                    </span>
                    <span className="text-gray-700 dark:text-gray-200">{it.likes_count ?? 0}</span>
                  </button>
                </div>
              </div>
            </div>
          );
        })}
        {/* sentinel：用于触发加载更多 */}
        <div ref={sentinelRef as any} className="col-span-full h-2" />
      </div>
      {/* 底部加载指示器（当有更多数据时显示） */}
      {page < totalPages && (
        <div className="mt-4 text-center text-sm text-gray-500 dark:text-gray-400">{t('my_work.loading_more')}</div>
      )}

      {/* 详情弹窗 */}
      <WorkDetailModal
        open={detailOpen}
        work={current}
        onClose={() => setDetailOpen(false)}
        onTogglePublic={handleTogglePublic}
        onDelete={handleDelete}
        onToggleLike={handleToggleLike}
      />
      {/* 删除确认弹窗（简单实现） */}
      {confirmOpen && (
        <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/40">
          <div className="bg-white dark:bg-[#111] rounded p-4 w-[90%] max-w-md">
            <div className="text-base text-gray-600 dark:text-gray-300 font-medium mb-2">{t('my_work.bulk_confirm_message')}</div>

            <div className="flex justify-end gap-2">
              <button onClick={() => setConfirmOpen(false)} className="px-3 py-1 rounded text-gray-600 dark:text-gray-300 bg-gray-100">{t('my_work.cancel')}</button>
              <button onClick={handleConfirmBulkDelete} className="px-3 py-1 rounded bg-red-500 text-white text-gray-600 dark:text-gray-300">{t('my_work.delete')}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MyWorkPage;

